package com.fliangyun.nsa.nsamanage.config;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fliangyun.nsa.nsamanage.entities.LogInfo;
import com.fliangyun.nsa.nsamanage.entities.User;
import com.fliangyun.nsa.nsamanage.service.impl.LogInfoServiceImpl;
import com.fliangyun.nsa.nsamanage.service.impl.SecureUserDetailsServiceImpl;
import com.fliangyun.nsa.nsamanage.web.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Rain
 * @date 2023年05月28日
 * @description
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 登录验证
     */
    @Autowired
    private SecureUserDetailsServiceImpl userDetailsService;
    @Autowired
    private LogInfoServiceImpl logInfoService;

    /**
     * 密码验证
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login", "/common/**", "/plugs/**").permitAll()
                .anyRequest().authenticated()
                .and()
                // 设置登录页面
                .formLogin().usernameParameter("username").passwordParameter("password").loginProcessingUrl("/ajaxLogin").loginPage("/login")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        // 登录成功
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out = response.getWriter();
                        User user = (User) authentication.getPrincipal();
                        // 写入登录日志
                        out.write(JSON.toJSONString(Result.success("登录成功", user)));
                        out.flush();
                        out.close();
                        request.getSession().setAttribute("currentUser", authentication.getPrincipal());
                        LogInfo logInfo = new LogInfo();
                        logInfo.setAction("登录");
                        logInfoService.save(logInfo);
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                        // 登录失败
                        Result<?> result = Result.fail("登录失败", 100);
                        if (exception instanceof BadCredentialsException) {
                            result.setMsg("用户名或者密码错误");
                        }
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out = response.getWriter();
                        //转成字符串以便输出
                        out.write(new ObjectMapper().writeValueAsString(result));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll().and().logout().deleteCookies("JSESSIONID")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        SecurityContextHolder.clearContext();
                        request.getSession().removeAttribute("currentUser");
                        Result<?> result = Result.success("退出成功", null);
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out = response.getWriter();
                        //转成字符串以便输出
                        out.write(new ObjectMapper().writeValueAsString(result));
                        out.flush();
                        out.close();
                    }
                })
                .and().sessionManagement().invalidSessionUrl("/login")
        ;
        http.formLogin();
        // 防止网站受到攻击
        http.csrf().disable();
        // 注销后跳转到登录页
        http.logout().logoutSuccessUrl("/login");
        // 防止iframe 造成跨域
        http.headers().frameOptions().disable();
    }

}
